package com.itheima.web.Servlet;

import com.itheima.Service.Impl.UserServiceImpl;
import com.itheima.Service.UserService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@WebServlet("/LoginServlet")
public class LoginServlet extends BaseServlet {
    private UserService userService = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从配置文件中得到相关的用户信息
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String checkCode = req.getParameter("checkCode");
        //从session会话域中获取得到的验证码
        Object checkCode1 = req.getSession().getAttribute("checkCode");

        if (checkCode.equalsIgnoreCase(checkCode)) {
            //判断验证码是否正确
            System.out.println("验证码正确,开始比较用户名密码...");
            //获取用户信息的配置文件的绝对路径

            boolean res =userService.Login(username,password);
            if (res) {

                //判断用户名密码
                // if (prop.containsKey(username) && password.equalsIgnoreCase(prop.getProperty(username))) {
                System.out.println("用户名密码正确...");

                HttpSession session = req.getSession();
                //创建cookie
                Cookie cookie = new Cookie("JSESSIONID", session.getId());
                //设置缓存时间
                cookie.setMaxAge(60 * 10);
              session.setAttribute("username",username);
                resp.addCookie(cookie);
                //登录成功 重定向到查看页面
                resp.sendRedirect(req.getContextPath()+"/stu/findAll");
            } else {
                System.out.println("用户名或密码错误...");
                //登录失败 重定向到登录页面
                resp.sendRedirect(req.getContextPath()+"/Login.html");
            }
        }else {
            resp.sendRedirect(req.getContextPath()+"/Login.html");
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

}
